#!/usr/bin/env python

import gtk
import pango
import gettext
import constants as iconstants
from mxit import handles
from signals import chatWindowSignals
#from signals import multimxTabSignals
from blend import const
from blend import conversation
from blend import parser
from blend import constants
import emoticons
import htmltextview
import gtk.keysyms
import gobject
import types
import time

gettext.install('blendIT','locale');


class multiMxTab:

   def __init__(self,blend,conv):
      self.conv = conv;
      self.blend = blend;
      
      #self.sigs = multimxTabSignals.signals(blend);
      self.cw = self.blend.gui.chatWindow;
      
      self.emoticons = self.cw.emoticons;
      self.parser = self.cw.parser;
      
      self.vbox = gtk.VBox();
      self.vbox.show();
      
      # Draw stuff
      hbox = gtk.HBox();
      hbox.pack_start(self.drawChatBox(),True,True,4);
      hbox.pack_end(self.drawBuddyList(),False,False,8);
      hbox.show();
      
      self.vbox.pack_start(hbox,True,True,4);
      self.vbox.pack_end(self.cw.controls(self.conv),False,False,4);

   def sendMessage(self,buddy,message):
      iter = self.findBuddy(buddy);
      if iter is -1:
         return;

      msg = message.message;
      msg = msg.replace("%","%%").replace("&","&amp;");
      
      if handles.MessageFlags.MARKUP in message.flags:
         m = str(self.parser.parse(msg,parser.MARKUP));
      else:
         m = str(self.parser.parse(msg));
     
      if handles.MessageFlags.CUSTOM_EMOTICONS in message.flags:
         m = self.emoticons.findCustomEmoticons(m);

      if type(message.time) == type(float(1)):
         t = message.time;
      else:
         t = float(time.mktime(message.time.timetuple())); 
         
      ti = time.strftime(self.blend.config.timeformat,time.localtime(t));

      if type(message.buddy) == types.StringType:
         colour = 'blue';
         name = message.buddy;
      else:
         colour = iconstants.colours[self.model.get_value(iter,2)];
         name = message.buddy.name;
      
      txt = '<div><span style="color: %s; font-size: small">(%s) </span>';
      txt += '<span style="color: %s; font-weight: bold">%s:  </span>';
      txt += '<span style="margin-left: 8px">%s</span><br/>\n</div>\n';
      mesg = txt % (colour,ti,colour,str(name),m);     
      self.conv.view.display_html(mesg);
      mark = self.conv.view.get_buffer().get_mark('end');
      self.conv.view.scroll_to_mark(mark,0.05,True,0.0,1.0);

      # Finally, check to see if we did have any custom emoticons
      # to download.
      if handles.MessageFlags.CUSTOM_EMOTICONS in message.flags:
         if m.find("customEmote") != -1:
            self.emoticons.getCustomEmoticons(self.conv,m);

   def addBuddy(self,buddy):
      # Add buddy to the list
      iter = self.findBuddy(buddy);
      if iter is -1:
         # How many buddies are we atm?
         rows = len(self.model);
         while rows > 10:
            rows = rows - 10;
         if rows < 0:
            rows = 0;
         colour = int(rows);

         col = iconstants.colours[colour];
         name = '<span style="color: %s">%s</span>' % (col,str(buddy.name));
         data = (name,str(buddy.name),colour);
         self.model.append(None,data);        
         self.systemMessage('<span style="color: %s">%s</span> joined the conversation' % (col,str(buddy.name)));

   def removeBuddy(self,buddy):
      # Remove from the list
      iter = self.findBuddy(buddy);
      if iter is not -1:
         self.model.remove(iter);
         message = "%s has left the conversation" % str(buddy.name);
         self.systemMessage(message);
   
   def systemMessage(self,message):
      msg = '<div>';
      msg += '<span style="color: %s; font-style: italic">%s</span>' % (iconstants.COLOUR_System,str(message));
      msg += '</div>';

      self.conv.view.display_html(msg);

   def findBuddy(self,buddy):
      iter = self.model.get_iter_first();
      while iter != None:
         j = self.model.get_value(iter,1);
         if j == buddy.name:
           return iter;
               
         iter = self.model.iter_next(iter);
      return -1;

   # This is just a usual htmlTextView screen
   def drawChatBox(self):
      self.conv.view = htmltextview.HtmlTextView()
      self.conv.view.connect('url-clicked',self.cw.sigs.on_url_clicked);
      self.conv.view.set_pixels_above_lines(4);
      self.conv.view.set_left_margin(6);
      self.conv.view.set_right_margin(6);
      self.conv.view.set_wrap_mode(gtk.WRAP_WORD);
      buf = self.conv.view.get_buffer();
      buf.create_mark("end",buf.get_end_iter(),False);
      self.conv.view.show();

      scrollWindow = gtk.ScrolledWindow();
      scrollWindow.set_policy(gtk.POLICY_NEVER,gtk.POLICY_AUTOMATIC);
      scrollWindow.add(self.conv.view);
      scrollWindow.show();

      return scrollWindow;
      
   # Buddy List for the users in the chat room
   def drawBuddyList(self):
      # ChatBuddy Name, ChatBuddy JID, Colour Index
      self.model = gtk.TreeStore(str,str,int);   
   
      self.tree = gtk.TreeView();
      self.tree.set_model(self.model);

      buddyCell = gtk.CellRendererText();
      buddy = gtk.TreeViewColumn(_("Buddy"),buddyCell,markup=1);
      buddy.add_attribute(buddyCell,'text',0);
      self.tree.append_column(buddy);

      self.tree.set_headers_visible(False);
      self.tree.show();
      scrollWindow = gtk.ScrolledWindow();
      scrollWindow.set_policy(gtk.POLICY_NEVER,gtk.POLICY_AUTOMATIC);
      scrollWindow.add(self.tree);
      scrollWindow.show();
      
      return scrollWindow;

      self.tree.set_enable_search(True);
